//
//  FaultDetectController.m
//  BalanceCar
//
//  Created by 郑信鸿 on 17/6/20.
//  Copyright © 2017年 郑信鸿. All rights reserved.
//

#import "FaultDetectController.h"
#import "ItemCellView.h"
#import "UIView+shadow.h"
#import "SeparateLineView.h"
#import "TBCycleView.h"
#import "BaseSendData.h"
#import "CarTravelModel.h"
#import "ByteTool.h"

@interface FaultDetectController ()

@property(nonatomic, strong)UIView *listView;
@property(nonatomic, strong)NSMutableArray *itemListViews;
@property(nonatomic, strong)UILabel *rateLabel;

@property(nonatomic, strong)UIColor *startColor;

@property(nonatomic, strong)UIColor *runingColor;

@property(nonatomic, strong)UIButton *startBtn;
@property(nonatomic, strong)TBCycleView *cycleView;

@property(nonatomic, strong)CarTravelModel *travelModel;

@property(nonatomic, assign)NSInteger count;

@property(nonatomic, strong)NSTimer *timer;

@end

@implementation FaultDetectController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = XHLocalizedString(@"Fault detection");
    self.startColor = [UIColor colorFromHexCode:@"#666666"];
    self.runingColor = [UIColor colorFromHexCode:@"#17c549"];
    self.itemListViews = [NSMutableArray array];
    // Do any additional setup after loading the view.
    [self establishTopView];
    [self bulidListView];
    self.count = 0;
    
    [BaseSendData sendTravelParamsOrder];

}


- (void)establishTopView{

    UIView *backView = [[UIView alloc] init];
    [self.view addSubview:backView];
    [backView mas_makeConstraints:^(MASConstraintMaker *make) {
       
        make.centerX.mas_offset(0);
        make.top.mas_offset(20);
        make.width.height.mas_offset(180);
    }];
    
    UIImageView *iconImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"check_round"]];
    [backView addSubview:iconImageView];
    self.cycleView = [[TBCycleView alloc] init];
    self.cycleView.backgroundColor = [UIColor clearColor];
    [backView addSubview:self.cycleView];
    [self.cycleView mas_makeConstraints:^(MASConstraintMaker *make) {
       
        make.center.mas_offset(0);
        make.width.height.mas_offset(200);
        
    }];
   //180x180
    [iconImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.mas_offset(0);
    }];
    
    self.rateLabel = [[UILabel alloc] init];
    self.rateLabel.textColor = self.startColor;
    [backView addSubview:self.rateLabel];
    self.rateLabel.text = @"0";
    self.rateLabel.font = [UIFont systemFontOfSize:24];
    [self.rateLabel mas_makeConstraints:^(MASConstraintMaker *make) {
       
        make.center.mas_offset(0);
    }];
    self.startBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:self.startBtn];
    [self.startBtn setBackgroundImage:[UIImage imageNamed:@"check_button_check"] forState:UIControlStateNormal];
    [self.startBtn setTitle:XHLocalizedString(@"Start to detect") forState:UIControlStateNormal];
    [self. startBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    UIControlState checkingState = UIControlStateDisabled;
    UIControlState checkedState = UIControlStateDisabled | UIControlStateSelected;
    [self.startBtn setBackgroundImage:[UIImage imageNamed:@"check_button_checking"] forState:checkingState];
    [self.startBtn setTitle:XHLocalizedString(@"detecting") forState:checkingState];
    [self.startBtn setTitleColor:[UIColor colorFromHexCode:@"#66666"] forState:checkingState];
    [self.startBtn setBackgroundImage:[UIImage imageNamed:@"check_button_checked"] forState:checkedState];
    [self.startBtn setTitle:XHLocalizedString(@"Detect complete") forState:checkedState];
    [self.startBtn setTitleColor:self.runingColor forState:checkedState];
    [self.startBtn addTarget:self action:@selector(checkAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.startBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(backView.mas_bottom).offset(20);
        make.centerX.mas_offset(0);
        make.width.mas_offset(120);
        make.height.mas_offset(40);
    }];
}

- (void)bulidListView{
    NSArray *titles = @[XHLocalizedString(@"Bus"),XHLocalizedString(@"Handlebar"),XHLocalizedString(@"Driving board"),XHLocalizedString(@"Electric motor"),XHLocalizedString(@"Battery")];
     NSArray *imageNames = @[@"check_listicon_line",@"check_listicon_hand",@"check_listicon_board",@"check_listicon_electrica",@"check_listicon_battery"];
    self.listView = [[UIView alloc] init];
    self.listView.backgroundColor = [UIColor whiteColor];
    [self.listView addShadowToView];
    [self.view addSubview:self.listView];
    CGFloat cellHeight = (kUIScreenHeight - 300 - 64) / titles.count;
  
    [self.listView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.mas_equalTo(self.startBtn.mas_bottom).offset(20);
        make.left.mas_offset(12);
        make.right.mas_offset(-12);
        make.height.mas_offset(cellHeight * imageNames.count);
        
    }];
    
    for (int i = 0; i<titles.count; i++) {
        ItemCellView *itemView = [[ItemCellView alloc] initWithImageName:imageNames[i] title:titles[i]];
        [self.listView addSubview:itemView];
        [self.itemListViews addObject:itemView];
    }
    
    [self.itemListViews mas_makeConstraints:^(MASConstraintMaker *make) {
       
        make.left.mas_offset(16);
        make.right.mas_offset(-16);
        
    }];
    [self.itemListViews mas_distributeViewsAlongAxis:MASAxisTypeVertical withFixedItemLength:cellHeight leadSpacing:0 tailSpacing:0];

    NSMutableArray *lines = [NSMutableArray array];
    for (int i = 0; i < titles.count - 1; i++) {
        SeparateLineView *line = [[SeparateLineView alloc] init];
        
        [self.listView addSubview:line];
        [lines addObject:line];
    }
    [lines mas_makeConstraints:^(MASConstraintMaker *make) {
       
        make.left.right.mas_offset(0);
    
    }];
    
    [lines mas_distributeViewsAlongAxis:MASAxisTypeVertical withFixedItemLength:0.5 leadSpacing:cellHeight tailSpacing:cellHeight];
   
    
    
}

- (void)checkAction:(UIButton *)btn{
    
    btn.enabled = NO;
    
   self.timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
    [self.timer fire];
    for (ItemCellView *cellView in self.itemListViews) {
        [cellView.tipImageView startLoading];
    }
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(10 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        Byte faultByte = [BaseAcceptData shareManager].travelModel.faultByte;
        
        Byte faults[8] = {};
        
        [ByteTool byteToBits:faults byte:faultByte];
        
        for (int i = 0; i < self.itemListViews.count; i ++) {
            
            ItemCellView *cellView = self.itemListViews[i];
            Byte fault = faults[i];
            
            [cellView.tipImageView stopLoadIsFail:fault];
        }
    });
}


- (void)timerAction{
    
    dispatch_async(dispatch_get_main_queue(), ^{
        
        [self.cycleView drawProgress:self.count / 100.0];
         self.rateLabel.text = [NSString stringWithFormat:@"%ld%%",(long)self.count];
        
    });
    
    self.count ++;
    if (self.count == 100) {
        
        [self.timer invalidate];
        
       self.startBtn.selected = YES;
    }
    
}

- (void)checkProgesscomplete{
   dispatch_queue_t globalQueue = dispatch_get_global_queue(0, 0);
    
    dispatch_sync(globalQueue, ^{
       
        int i = 9;
        while (i) {
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                self.rateLabel.text = [NSString stringWithFormat:@"%d%%",i * 10];
                [self.cycleView drawProgress:i * 0.1];
                
            });
            
            [NSThread sleepForTimeInterval:0.3];
            i --;
        }

        
    });
    
    
}

- (void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
